package org.kolonitsky.translator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Alex.Kolonitsky
 */

public class TranslatorCacheDecorator extends BaseTranslator {

    protected static final Log LOG = LogFactory.getLog(TranslatorCacheDecorator.class);

    private final TranslatorCache cache;
    private final Translator translator;

    public TranslatorCacheDecorator(TranslatorCache cache, Translator translator) {
        super(cache.from(), cache.to());

        this.cache = cache;
        this.translator = translator;
    }

    public TranslatorCacheDecorator(TranslatorCache cache, Translator ... translators) {
        this(cache, new TranslatorChain(translators));
    }

    public String translate(String text) {
        if (text == null || text.length() == 0) {
            return text;
        }

        String res = cache.translate(text);
        if (res != null && res.length() > 0) {
            LOG.debug("translate - cache  - '" + text + "'");
            return res;
        }

        res = translator.translate(text);
        if (res != null) {
            cache.put(text, res);
        }
        return res;
    }
}
